<?php

namespace App\Http\Controllers\UI;

use App\Miya\Models\Area;
use App\Miya\Models\Classify;
use App\Miya\Models\Info;
use App\Miya\Models\Module;
use App\Miya\Models\SearchRecord;
use Diglactic\Breadcrumbs\Breadcrumbs;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Route;

class ClassifyController extends CommonController
{
    public function __construct()
    {
        //勿删 禁止缓存页面中间件 page-cache
    }

    public function pc(Module $module, Classify $classify)
    {
        $data = $this->buildData($module, $classify);
        if ($data instanceof RedirectResponse) {
            return $data;
        }

        return view($classify->tql ?? $module->classify_tql, $data);
    }

    public function area(Area $area, Module $module, Classify $classify)
    {
        $data = $this->buildData($module, $classify, $area);
        if ($data instanceof RedirectResponse) {
            return $data;
        }
        $data['title'] = sprintf('%s_%s分站', $data['title'], $area->name);
        return view($classify->tql ?? $module->classify_tql, $data);
    }

    public function mobile(Module $module, Classify $classify)
    {
        $data = $this->buildData($module, $classify);
        if ($data instanceof RedirectResponse) {
            return $data;
        }
        return view($classify->wap_tql ?? $module->wap_classify_tql, $data);
    }

    protected function buildData($module, $classify, $area = null)
    {
        $data = [];
        $data['area'] = $area ?? new Area();
        $module = Module::with(['classifies' => function ($query) {
            $query->where('status', 1);
            $query->orderBy('rank');
        }, 'classifies.module'])->find($module->id);
        $module->classifies = $module->classifies->toTree();
        $data['module'] = $module;
        $data['classify'] = $classify;
        $data['breadcrumb'] = Breadcrumbs::render('classify', ['module' => $module, 'classify' => $classify]);

        //有分类信息的情况
        if (!request()->route()->hasParameter('classify')) {
            $data['title'] = $module->title ?? sprintf(
                    '%s_%s',
                    $module->name,
                    config('web.name')
                );
            if ($area) {
                $data['keywords'] = miya('keyword')->derivatives($area, $module->keyword, [1])[0];
            } else {
                $data['keywords'] = $module->keyword->keyword ?? '';
            }
            $data['description'] = $module->description ?? config('web.description');
        } else {
            $data['title'] = $classify->title ?? sprintf(
                    '%s_%s',
                    $classify->name ?? '总',
                    config('web.name')
                );
            if ($area) {
                $data['keywords'] = miya('keyword')->derivatives($area, $classify->keyword, [1])[0];
            } else {
                $data['keywords'] = $classify->keyword->keyword ?? '';
            }
            $data['description'] = $classify->description ?? config('web.description');
        }

        $builder = Info::whereHas('classify')->where('status', 1)
            ->with(Info::$DefaultRelationships)
            ->where('module_id', $module->id)
            ->where(function ($query) use ($classify) {
                if (request()->route()->hasParameter('classify')) {
                    $classifies = request()->route('classify')->descendants->pluck('id');
                    $classifies[] = request()->route('classify')->id;
                    $query->whereIn('classify_id', $classifies);
                }
            })->where(function ($query) {
                $query->where('is_delayed', 2)->orWhere(function ($query) {
                    $query->where('is_delayed', 1)->where('delayed_at', '<=', now());
                });
            });

        // 单页模式检测
        if ($module->one_info == 1) {
            if ($builder->count() == 1) {
                $routesMap = [
                    'pc.classify' => 'pc.info',
                    'area.classify' => 'area.info',
                    'm.classify' => 'm.info',
                ];
                $route = Route::currentRouteName();
                $oneInfo = $builder->first();
                if ($route == 'area.classify') {
                    $routeData = [$area->tag, $oneInfo->module->tag, $oneInfo->classify->tag, $oneInfo->tag];
                } else {
                    $routeData = [$oneInfo->module->tag, $oneInfo->classify->tag, $oneInfo->tag];
                }
                return redirect()->route($routesMap[$route], $routeData);
            }
        }

        //信息排序
        $builder = Info::rankByType($builder, $module->info_rank_type);

        $infos = $builder->where(function ($query) {
            //信息名称搜索
            if (!empty(request()->input('search'))) {
                //添加搜索记录
                if (config('miya.search_record') && request()->has('search')) {
                    $record = [
                        'search' => request()->input('search'),
                        'module_id' => request()->route('module')->id,
                    ];

                    $hash = md5(json_encode($record));
                    $record['hash'] = $hash;

                    $record = SearchRecord::firstOrCreate(['hash' => $hash], $record);
                    $record->count += 1;
                    $record->save();
                }

                $query->where('name', 'like', '%' . request()->input('search') . '%');
            }
            //信息types搜索
            if (request()->has('types')) {
                foreach (request()->input('types') as $type) {
                    if ($type) {
                        $query->whereHas('info_types', function ($query) use ($type) {
                            $query->where('value', $type);
                        });
                    }
                }
            }
        })->paginate($module->info_paginate_num);

        // 格式化信息
        foreach ($infos as $info) {
            $info->avatar && $info->avatar = asset('uploads/' . $info->avatar);
            $info->images = array_map(function ($img) {
                return asset('uploads/' . $img);
            }, $info->images);
            $info->keywords = $info->getKeywords();
        }
        $data['infos'] = $infos;
        return $data;
    }
}
